﻿using MyNotepadInterface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyNotepadMain
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void tsmiFormat_Click(object sender, EventArgs e)
        {
            //清空已经加载的插件
            tsmiFormat.DropDownItems.Clear();

            //加载Plugins目录下所有的插件
            LogPlugins();
        }

        private void LogPlugins()
        {
            //定义一个接口约束
            Type typeIEditor = typeof(IEditor);

            //设置插件目录
            //第一种方法
            //string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Plugins");
            //第二种方法
            string path = AppDomain.CurrentDomain.BaseDirectory + "Plugins";

            //搜索插件目录下所有的*.dll
            string[] dlls = System.IO.Directory.GetFiles(path, "*.dll");

            //动态加载每个DLL 文件
            foreach (string dllPath in dlls)
            {
                //加载DLL文件
                Assembly assembly = Assembly.LoadFile(dllPath);

                //获取DLL中所有Public类型方法和属性
                Type[] types = assembly.GetExportedTypes();

                //遍历判断实现了接口的Public方法和属性
                foreach (Type userType in types)
                {
                    if (typeIEditor.IsAssignableFrom(userType) && !userType.IsAbstract)
                    {
                        //创建一个对象
                        IEditor plugin = (IEditor)Activator.CreateInstance(userType);

                        //把插件添加到菜单栏上面
                        ToolStripItem tsi = tsmiFormat.DropDownItems.Add(plugin.Name);
                        //为该菜单添加一个单击事件
                        tsi.Click += new EventHandler(tsi_Click);
                        tsi.Tag = plugin;
                    }
                }

            }

        }

        void tsi_Click(object sender, EventArgs e)
        {
            ToolStripItem tsi = sender as ToolStripItem;
            if (tsi != null)
            {
                IEditor editorPlugin = tsi.Tag as IEditor;
                //运行该插件
                editorPlugin.Run(this.textBox1);
                //TODO: 需要检车插件窗口为什么不能调用
            }
        }
    }
}
